from elasticsearch import Elasticsearch
import os
import time

# 使用elasticsearch库创建Elasticsearch客户端实例
#es = Elasticsearch([{'host': '192.168.80.35', 'port': 9200, 'scheme': 'https'}])

es = Elasticsearch(["https://192.168.80.35:9200"],http_auth=('elastic', '123456'),verify_certs=False)
#es = Elasticsearch("http://127.0.0.1:9200", basic_auth=('elastic', '8ecP5-m+U7Ru-qDp_*C9'))

def getAllIndex():
    index_names = es.cat.indices(format="json")
    for index in index_names:
        indexId=index['index']
        
        if indexId.startswith("z", 0):
            print(indexId)

        #es.indices.delete(index=index['index'])


def create_index(file_path, index_name):
    # 检查索引是否存在
    if not es.indices.exists(index=index_name):
        # 创建索引映射
        mapping = {
            "mappings": {
                "properties": {
                    "file": {
                        "type": "text"
                    }
                }
            }
        }
        es.indices.create(index=index_name, body=mapping)
        print(f"索引 '{index_name}' 创建成功。")

        # 检查文件是否存在
        if os.path.exists(file_path):
            with open(file_path, 'r', encoding='utf-8') as file:
                content = file.read()
                # 按 '#####' 分隔内容
                content = content.replace('#####', '$$$$$')
                # segments = content.split('#####')
                segments = content.split('$$$$$')

                for segment in segments:
                    # 创建文档
                    doc = {
                        "file": segment.strip()  # 去掉首尾空白
                    }
                    # 将文档添加到索引
                    es.index(index=index_name, document=doc)
                    # print("已添加片段到索引:", segment.strip()[:30], "...")  # 打印片段的前30个字符
        else:
            print(f"文件 '{file_path}' 不存在。")
        time.sleep(1)
    else:
        print(f"索引 '{index_name}' 已存在，未执行任何操作。")


def search_and_save_results(question, index_name):
    size = 10

    # 构建搜索查询
    query = {
        "query": {
            "bool": {
                "must": [
                    {"match": {"file": question}}  # 确保字段名与索引中一致
                ]
            }
        },
        "size": size  # 设置返回结果的数量
    }



    try:
        # 执行搜索
        results = es.search(index=index_name, body=query)

        # 处理结果并构建字符串
        hits = results['hits']['hits']

        # 初始化一个空字符串
        documents_string = ""

        for hit in hits:
            document_info = f"{hit['_source']['file']}"
            # 将每个文档信息添加到字符串中
            documents_string += document_info + "\n#####\n"  # 用分隔符隔开

        # 去掉最后一个分隔符
        documents_string = documents_string.rstrip("\n#####\n")

        return documents_string  # 返回包含所有文档信息的字符串

    except Exception as e:
        return f"Error occurred: {e}"  # 返回错误信息

"""

indexId = "zb1217"
path = "C:\\Users\\user\\Desktop\\测试2\\91055d05c2a14f50890df01f06d83875-招标\\商务文件-拆分后.txt"
create_index(path, indexId)
test = search_and_save_results("招标项目名称", indexId)
print(test[:5000])

"""

getAllIndex()
